package com.working.home.ui.search

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.observe
import com.alibaba.android.arouter.facade.annotation.Route
import com.working.home.R
import com.working.home.databinding.HomeActivitySearchBinding
import com.working.home.ui.ArticleAdapter
import com.working.libbase.base.BaseActivity
import com.working.libbase.route.RoutePath
import com.working.libcommon.adapter.setPagingAdapter
import org.koin.android.ext.android.bind
import org.koin.androidx.viewmodel.ext.android.viewModel

@Route(path = RoutePath.HOME.SEARCH)
class SearchActivity : BaseActivity() {
    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, SearchActivity::class.java)
            context.startActivity(starter)
        }
    }

    private val mBinding by binding<HomeActivitySearchBinding>(R.layout.home_activity_search)

    private val mViewModel: SearchViewModel by viewModel()

    private val mAdapter: ArticleAdapter by lazy {
        ArticleAdapter(mViewModel.dataSource)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white)
        mBinding.apply {

            lifecycleOwner = this@SearchActivity
            searchResult.setPagingAdapter(
                this@SearchActivity,
                mAdapter
            )
            mViewModel.searchKey.observe(this@SearchActivity) {
                mAdapter.refresh()
            }
        }

        immerseColor(Color.RED)
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.add(0, R.id.action_search, 0, "搜索")
            ?.setIcon(R.drawable.ic_search)
            ?.setActionView(SearchView(this).apply {
                maxWidth = Integer.MAX_VALUE
                onActionViewExpanded()
                queryHint = "发现更多干货"
                isSubmitButtonEnabled = true
                setOnQueryTextListener(mViewModel.queryTextListener)
            })
            ?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return super.onCreateOptionsMenu(menu)

    }
}